package net.crazyadam.activity;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import net.crazyadam.audio.Constant;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Copyright by <a href="http://crazyadam.net"><em><i>Joseph J.C. Tang</i></em></a> <br/>
 * Email: <a href="mailto:jinntrance@gmail.com">jinntrance@gmail.com</a>
 *
 * @author joseph
 * @version 1.0
 * @since 10/18/12 5:09 PM
 */
public class AudioRecorderNoFFT extends Thread {
    private boolean receivable = true;
    private int inputBlockSize = 32;
    private Queue<AudioData> queue = new LinkedList<AudioData>();

    @Override
    public void run() {
        int audioBuf = AudioRecord.getMinBufferSize(Constant.SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 2;

        // Set up the audio input.
        AudioRecord audioInput = new AudioRecord(MediaRecorder.AudioSource.MIC, Constant.SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, audioBuf);
        audioInput.startRecording();
        int inputBufferIndex = 0;
        short[] buffer = new short[inputBlockSize];
        while (receivable) {

            int readSize = inputBlockSize;
            int space = inputBlockSize - inputBufferIndex;
            if (readSize > space)
                readSize = space;
            int index = inputBufferIndex;
            int nread = audioInput.read(buffer, index, readSize);//read size
            if (!receivable)
                break;
            if (nread < 0) {
                receivable = false;
                break;
            }
            int end = inputBufferIndex + nread;
            if (end >= inputBlockSize) {
                inputBufferIndex = 0;
                buffer = new short[inputBlockSize];
            } else
                inputBufferIndex = end;
        }
        audioInput.stop();
    }

    public void setBlockSize(int inputBlockSize) {
        this.inputBlockSize = inputBlockSize;
    }

    public Queue<AudioData> getQueue() {

        return queue;
    }

    public class AudioData {
        private short[] data;

        public AudioData(short[] data) {
            this.data = data;
        }

        public short[] getData() {
            return data;
        }
    }

    public void stopRecorder() {
        this.receivable = false;
    }
}
